using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.Wpf;

namespace WebBrowserApp
{
    public partial class MainWindow : Window
    {
        private readonly PageInfoCaptureService _captureService;

        public MainWindow()
        {
            InitializeComponent();
            _captureService = new PageInfoCaptureService();
            InitializeWebView();
        }

        private async void InitializeWebView()
        {
            try
            {
                await WebView.EnsureCoreWebView2Async();
                WebView.CoreWebView2.Settings.IsWebMessageEnabled = true;
                WebView.CoreWebView2.Settings.AreDefaultScriptDialogsEnabled = true;
                
                // 默认加载百度
                WebView.Source = new Uri("https://www.baidu.com");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化浏览器失败: {ex.Message}", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void NavigateButton_Click(object sender, RoutedEventArgs e)
        {
            NavigateToUrl();
        }

        private void UrlTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                NavigateToUrl();
            }
        }

        private void NavigateToUrl()
        {
            var url = UrlTextBox.Text.Trim();
            if (string.IsNullOrEmpty(url))
                return;

            try
            {
                if (!url.StartsWith("http://") && !url.StartsWith("https://"))
                {
                    url = "https://" + url;
                }
                WebView.Source = new Uri(url);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"无效的URL: {ex.Message}", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void BackButton_Click(object sender, RoutedEventArgs e)
        {
            if (WebView.CoreWebView2?.CanGoBack == true)
            {
                WebView.CoreWebView2.GoBack();
            }
        }

        private void ForwardButton_Click(object sender, RoutedEventArgs e)
        {
            if (WebView.CoreWebView2?.CanGoForward == true)
            {
                WebView.CoreWebView2.GoForward();
            }
        }

        private void RefreshButton_Click(object sender, RoutedEventArgs e)
        {
            WebView.CoreWebView2?.Reload();
        }

        private void WebView_SourceChanged(object? sender, CoreWebView2SourceChangedEventArgs e)
        {
            if (WebView.CoreWebView2 != null)
            {
                Dispatcher.Invoke(() =>
                {
                    UrlTextBox.Text = WebView.CoreWebView2.Source;
                });
            }
        }

        private void WebView_NavigationCompleted(object? sender, CoreWebView2NavigationCompletedEventArgs e)
        {
            if (e.IsSuccess)
            {
                Dispatcher.Invoke(() =>
                {
                    PageInfoTextBlock.Text = "页面加载完成，点击'抓取页面信息'按钮获取详细信息...";
                });
            }
            else
            {
                Dispatcher.Invoke(() =>
                {
                    PageInfoTextBlock.Text = $"页面加载失败: {e.WebErrorStatus}";
                });
            }
        }

        private async void CaptureInfoButton_Click(object sender, RoutedEventArgs e)
        {
            if (WebView.CoreWebView2 == null)
            {
                MessageBox.Show("浏览器未初始化", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            try
            {
                PageInfoTextBlock.Text = "正在抓取页面信息...";
                
                var pageInfo = await _captureService.CapturePageInfoAsync(WebView.CoreWebView2);
                
                PageInfoTextBlock.Text = FormatPageInfo(pageInfo);
            }
            catch (Exception ex)
            {
                PageInfoTextBlock.Text = $"抓取信息时出错: {ex.Message}\n{ex.StackTrace}";
            }
        }

        private string FormatPageInfo(PageInfo pageInfo)
        {
            return $@"页面信息抓取结果
====================

【基本信息】
URL: {pageInfo.Url}
标题: {pageInfo.Title}
加载时间: {pageInfo.LoadTime:yyyy-MM-dd HH:mm:ss}

【页面内容】
文本长度: {pageInfo.TextContentLength} 字符
HTML长度: {pageInfo.HtmlLength} 字符

【链接信息】
总链接数: {pageInfo.LinkCount}
所有链接:
{string.Join("\n", pageInfo.Links.Select((link, i) => $"{i + 1}. {link}"))}

【图片信息】
总图片数: {pageInfo.ImageCount}
所有图片:
{string.Join("\n", pageInfo.Images.Select((img, i) => $"{i + 1}. {img}"))}

【表单信息】
表单数量: {pageInfo.FormCount}

【Meta信息】
{string.Join("\n", pageInfo.MetaTags.Select(m => $"- {m.Key}: {m.Value}"))}

【脚本信息】
脚本数量: {pageInfo.ScriptCount}

【样式信息】
样式表数量: {pageInfo.StyleSheetCount}

【完整HTML内容】
{pageInfo.HtmlContent}
";
        }
    }
}

